import {
  createContext,
  PropsWithChildren,
  useContext,
  useState,
  useCallback,
} from "react";
import SignIn from "../sign-in/SignIn";

interface ContextValue {
  token: string;
  logout: () => void;
}
const context = createContext<ContextValue>({
  token: "",
  logout: () => {},
});
context.displayName = "UserCotnext";

const defaultToken =
  sessionStorage.getItem("token") || localStorage.getItem("token");

function applyToken(token: string) {
  sessionStorage.setItem("token", token);
}

interface UserProviderProps {}

export const UserProvider = ({
  children,
}: PropsWithChildren<UserProviderProps>) => {
  const [token, _setToken] = useState(defaultToken);
  const setToken = useCallback((token: string) => {
    _setToken(token);
    applyToken(token);
  }, []);

  const logout = useCallback(async () => {
    //if (userResult.value) {
    //  localStorage.removeItem(`about-${userResult.value.UserID}`);
    // }
    //await logoutUser();
    setToken("");
    //setUser({ loading: false, value: undefined, error: undefined });
  }, [setToken]);
  if (!token) {
    return <SignIn></SignIn>;
  }
  return (
    <context.Provider value={{ token, logout }}>{children}</context.Provider>
  );
};
export const useToken = () => {
  return useContext(context).token;
};

export const useLogout = () => {
  return useContext(context).logout;
};
